<template>
  <div class="app-container">
    <el-card>
      <el-row
        :gutter="10"
        class="mb8"
        type="flex"
        justify="space-between"
        style="margin-bottom: 20px"
      >
        <el-col :span="6"
          ><span style="font-size: large">快速查询</span></el-col
        >
      </el-row>
      <!-- el-form 用于渲染查询表单，:model 绑定表单数据，:inline 设置为行内模式 -->
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="110px"
      >
        <el-form-item label="单据编号" prop="vbillcode">
          <el-input
            v-model="queryParams.vbillcode"
            placeholder="请输入单据编号"
            clearable
            style="width: 240px"
            @input="trimInput('vbillcode')"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="单据日期" prop="dbilldate">
          <el-date-picker
            v-model="queryParams.dbilldate"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 240px"
          >
          </el-date-picker>
        </el-form-item>

        <!-- 定义两个 el-option 选项，分别对应：未收货:0，已收货:1,已验收:2,已上架:3，已作废:9) -->
        <!-- <el-form-item label="WMS单据状态" prop="billStatus">
          <el-select v-model="queryParams.billStatus" placeholder="请选择单据状态" clearable style="width: 240px">
            <el-option label="未收货" value="0"></el-option>
            <el-option label="已收货" value="1"></el-option>
            <el-option label="已验收" value="2"></el-option>
            <el-option label="已上架" value="3"></el-option>
            <el-option label="已请验" value="4"></el-option>
            <el-option label="已作废" value="9"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="单据状态" prop="fbillflag">
          <el-select
            v-model="queryParams.fbillflag"
            placeholder="请选择NCC单据状态"
            clearable
            style="width: 240px"
          >
            <el-option label="作废" value="1"></el-option>
            <el-option label="自由" value="2"></el-option>
            <el-option label="签字" value="3"></el-option>
            <el-option label="审核" value="4"></el-option>
            <el-option label="审核中" value="5"></el-option>
            <el-option label="审核不通过" value="6"></el-option>
            <el-option label="已调差状态" value="7"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓库" prop="cwarehouseid">
          <el-select
            v-model="queryParams.cwarehouseid"
            placeholder="请选择仓库"
            size="small"
            filterable
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in NccStockOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="物料" prop="material">
          <el-select v-model="queryParams.material" placeholder="请输入物料" clearable style="width: 240px" remote
            :remote-method="searchSelectNccMaterial" :loading="loading" filterable>
            <el-option v-for="item in materialNameOptions" :key="item.pk" :label="item.name" :value="item.pk" />
          </el-select>
        </el-form-item> -->

        <!-- 表单操作项:查询/重置按钮 -->
        <el-form-item style="margin-left: 45px">
          <el-button type="primary" icon="Search" @click="handleQuery"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>

        <!-- <el-form-item>
          <el-button type="success" @click="handleMultipleConfirm">多选确认</el-button>
        </el-form-item> -->
      </el-form>
    </el-card>

    <!-- 表格部分 -->
    <el-card class="mt20">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"
          ><span style="font-size: large">其他出库单</span></el-col
        >
        <!-- <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['order:purchase:add']">创建其他入库单</el-button>
        </el-col> -->
      </el-row>
      <el-table
        :data="headerList"
        v-loading="loading"
        border
        class="mt20"
        :row-key="(row) => row.vbillcode"
        :expand-row-keys="expandKeys"
        @expand-change="handleExpandChange"
        @selection-change="handleSelectionChange"
        ref="tableRef"
      >
        <!-- 单据明细 -->
        <el-table-column type="expand" width="40">
          <template #default="{ row }">
            <div style="padding: 0 50px 20px 50px">
              <!-- <h3>单据明细</h3> -->
              <el-row
                :gutter="10"
                class="mb8"
                type="flex"
                justify="space-between"
              >
                <el-col :span="6"
                  ><span style="font-size: large">单据明细</span></el-col
                >
                <!-- <el-col :span="1.5">
                  <el-button type="primary" plain icon="Plus" @click="handleAdd(row)"
                    v-hasPermi="['order:purchase:add']">创建其他出库单</el-button>
                </el-col> -->
              </el-row>
              <!-- 修改此处的数据绑定，使用 row.detailData 获取对应明细数据 -->
              <el-table :data="row.detailData" border>
                <el-table-column
                  prop="crowno"
                  label="行号"
                  align="center"
                  width="50"
                />
                <el-table-column label="物料信息" align="center">
                  <template #default="{ row }">
                    <div v-if="row.cmaterialvid">
                      编码：{{ row.cmaterialvid.code }}
                    </div>
                    <div v-if="row.cmaterialvid">
                      名称：{{ row.cmaterialvid.name }}
                    </div>
                    <!-- <div v-if="row.cmaterialvid">主键：{{ row.cmaterialvid.pk }}</div> -->
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="GMP码" label="GMP码" align="center" />
                <el-table-column prop="规格" label="规格" align="center" />
                <el-table-column prop="型号" label="型号" align="center" /> -->
                <el-table-column label="物料管理信息" align="center">
                  <template #default="{ row }">
                    <div v-if="row.additionMap">
                      GMP码：{{ row.additionMap.graphid }}
                    </div>
                    <div v-if="row.additionMap">
                      型号：{{ row.additionMap.materialtype }}
                    </div>
                    <div v-if="row.additionMap">
                      规格：{{ row.additionMap.materialspec }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="主单位信息" align="center">
                  <template #default="{ row }">
                    <div v-if="row.cunitid">编码：{{ row.cunitid.code }}</div>
                    <div v-if="row.cunitid">名称：{{ row.cunitid.name }}</div>
                    <!-- <div v-if="row.cunitid">主键：{{ row.cunitid.pk }}</div> -->
                  </template>
                </el-table-column>
                <el-table-column label="单位信息" align="center">
                  <template #default="{ row }">
                    <div v-if="row.castunitid">
                      编码：{{ row.castunitid.code }}
                    </div>
                    <div v-if="row.castunitid">
                      名称：{{ row.castunitid.name }}
                    </div>
                    <!-- <div v-if="row.castunitid">主键：{{ row.castunitid.pk }}</div> -->
                  </template>
                </el-table-column>
                <el-table-column
                  prop="nshouldnum"
                  label="应发主数量"
                  align="center"
                />
                <el-table-column
                  prop="nshouldassistnum"
                  label="应发数量"
                  align="center"
                />
                <el-table-column
                  prop="nnum"
                  label="实发主数量"
                  align="center"
                />
                <el-table-column
                  prop="nassistnum"
                  label="实发数量"
                  align="center"
                />
                <el-table-column
                  prop="vchangerate"
                  label="换算率"
                  align="center"
                />
                <el-table-column
                  label="库存状态"
                  align="center"
                  prop="cstateid"
                >
                  <template #default="{ row }">
                    <dict-tag
                      :options="dict.type.inventory_status_type"
                      :value="row.cstateid"
                    ></dict-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="vbatchcode"
                  label="批次号"
                  align="center"
                />
                <el-table-column
                  prop="vvendbatchcode"
                  label="供应商批次号"
                  align="center"
                />
                <el-table-column label="供应商信息" align="center">
                  <template #default="{ row }">
                    <div v-if="row.cvendorid">
                      编码：{{ row.cvendorid.code }}
                    </div>
                    <div v-if="row.cvendorid">
                      名称：{{ row.cvendorid.name }}
                    </div>
                    <!-- <div v-if="row.cvendorid">主键：{{ row.cvendorid.pk }}</div> -->
                  </template>
                </el-table-column>
                <el-table-column
                  prop="vbcdef2"
                  label="供应商代码"
                  align="center"
                />
                <el-table-column
                  prop="vbcdef1"
                  label="合箱说明"
                  align="center"
                />
                <el-table-column
                  prop="vbcdef3"
                  label="包材版本"
                  align="center"
                />
                <el-table-column label="出库日期" align="center">
                  <template #default="{ row }">{{
                    formatDate(row.dbizdate)
                  }}</template>
                </el-table-column>
                <el-table-column label="生产日期" align="center">
                  <template #default="{ row }">{{
                    formatDate(row.dproducedate)
                  }}</template>
                </el-table-column>
                <el-table-column label="失效日期" align="center">
                  <template #default="{ row }">{{
                    formatDate(row.dvalidate)
                  }}</template>
                </el-table-column>
                <!-- <el-table-column prop="生产厂家信息" label="生产厂家信息" align="center" /> -->
                <el-table-column label="生产厂商信息" align="center">
                  <template #default="{ row }">
                    <div v-if="row.cproductorid">
                      编码：{{ row.cproductorid.code }}
                    </div>
                    <div v-if="row.cproductorid">
                      名称：{{ row.cproductorid.name }}
                    </div>
                    <!-- <div v-if="row.cproductorid">主键：{{ row.cproductorid.pk }}</div> -->
                  </template>
                </el-table-column>
                <el-table-column
                  prop="vapprovalnumber_148"
                  label="批准文号"
                  align="center"
                />
                <el-table-column label="持有人/注册人" align="center">
                  <template #default="{ row }">
                    <!-- <div v-if="row.pk_holder_148">编码：{{ row.pk_holder_148.code }}</div> -->
                    <div v-if="row.pk_holder_148">
                      {{ row.pk_holder_148.name }}
                    </div>
                    <!-- <div v-if="row.pk_holder_148">主键：{{ row.pk_holder_148.pk }}</div> -->
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>

        <!-- 单选框 -->
        <!-- <el-table-column type="selection" width="45" :reserve-selection="true" /> -->

        <!-- 单据表头 -->
        <el-table-column label="单据编号" align="center" width="80">
          <template #default="{ row }">{{ row.vbillcode }}</template>
        </el-table-column>
        <el-table-column label="单据日期" align="center" width="80">
          <template #default="{ row }">{{
            formatDate(row.dbilldate)
          }}</template>
        </el-table-column>
        <el-table-column label="需求日期" align="center" width="80">
          <template #default="{ row }">{{ formatDate(row.vdef3) }}</template>
        </el-table-column>
        <el-table-column label="仓库信息" align="center" min-width="100">
          <template #default="{ row }">
            <div v-if="row.cwarehouseid">编码：{{ row.cwarehouseid.code }}</div>
            <div v-if="row.cwarehouseid">名称：{{ row.cwarehouseid.name }}</div>
            <!-- <div v-if="row.cwarehouseid">主键：{{ row.cwarehouseid.pk }}</div> -->
          </template>
        </el-table-column>
        <el-table-column label="出入库类型" align="center">
          <template #default="{ row }">
            <dict-tag
              :options="dict.type.other_out_type"
              :value="row.ctrantypeid"
            ></dict-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="交易类型编码" align="center" width="80">
          <template #default="{ row }">{{ row.vtrantypecode }}</template>
        </el-table-column> -->
        <!-- <el-table-column label="单据状态" align="center" width="80">
          <template #default="{ row }">{{ row.fbillflag }}</template>
        </el-table-column> -->
        <el-table-column label="单据状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.fbillflag)">
              {{ getBillStatus(row.fbillflag) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="80">
          <template #default="{ row }">{{ row.vnote }}</template>
        </el-table-column>
        <!-- <el-table-column label="应出总数量" align="center" width="80">
          <template #default="{ row }">{{ row.ntotalpiece }}</template>
        </el-table-column> -->
        <el-table-column label="实出总数量" align="center" width="80">
          <template #default="{ row }">{{ row.ntotalnum }}</template>
        </el-table-column>
        <el-table-column label="业务员(领料)" align="center" min-width="100">
          <template #default="{ row }">
            <div v-if="row.cbizid">编码：{{ row.cbizid.code }}</div>
            <div v-if="row.cbizid">名称：{{ row.cbizid.name }}</div>
            <!-- <div v-if="row.cbizid">主键：{{ row.cbizid.pk }}</div> -->
          </template>
        </el-table-column>
        <el-table-column label="部门(领料)" align="center" min-width="100">
          <template #default="{ row }">
            <div v-if="row.cdptid">编码：{{ row.cdptid.code }}</div>
            <div v-if="row.cdptid">名称：{{ row.cdptid.name }}</div>
            <!-- <div v-if="row.cdptid">主键：{{ row.cdptid.pk }}</div> -->
          </template>
        </el-table-column>
        <el-table-column label="制单人信息" align="center" min-width="100">
          <template #default="{ row }">
            <div v-if="row.billmaker">编码：{{ row.billmaker.code }}</div>
            <div v-if="row.billmaker">名称：{{ row.billmaker.name }}</div>
            <!-- <div v-if="row.billmaker">主键：{{ row.billmaker.pk }}</div> -->
          </template>
        </el-table-column>
        <el-table-column label="制单时间" align="center" width="80">
          <template #default="{ row }">{{
            formatDate(row.dmakedate)
          }}</template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <div style="margin: 5px">
              <el-button
                link
                size="small"
                type="primary"
                plain
                @click="toggleExpand(row)"
                >{{
                  expandedRows.includes(row.vbillcode) ? "收起" : "查看"
                }}</el-button
              >
            </div>
            <div style="margin: 5px">
              <el-button
                link
                size="small"
                type="success"
                plain
                @click="handleConfirm(row)"
               :disabled="confirmLoadingMap[row.vbillcode]"
                v-if="
                  String(row.isConfirm) !== '1' && String(row.fbillflag) !== '3'
                "
                v-hasPermi="['order:otherout:confirm']"
              >
                {{ confirmLoadingMap[row.vbillcode] ? "确认中..." : "确认" }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float: right; margin: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
// 获取NCC其他出库单
import { getOtherOutboundNccInfo } from "@/api/supply/otherSupply.js";

// 获取对WMS确认NCC其他出库单的接口
import { createOtherOutboundConfirm } from "@/api/supply/otherSupply.js";

// 引入下拉框方法组件
import SearchSelect from "@/views/components/dropDown/searchSelect.js";

export default {
  // 用于存储需要加载的字典类型
  dicts: ["other_out_type", "inventory_status_type"],
  data() {
    return {
      nccList: [], // 存储NCC列表数据
      currentPage: 1, // 当前页
      pageSize: 5, // 每页显示条数
      total: 0, // 总条目数，需从后端返回
      loading: false, // 控制加载状态
      queryParams: {
        startDate: "", // 示例开始日期
        endDate: "", // 示例结束日期
        billStatus: "", // WMS单据状态
        fbillflag: "", // NCC单据状态
        cwarehouseid: "", // 仓库
        material: "", // 物料
      },
      headerList: [],
      detailsList: [],
      dbilldate: [], // 日期范围初始化为空数组
      expandKeys: [], // 当前展开的行的 key 数组
      expandedRows: [], // 记录已展开行的 key
      responseData: [], // 初始化 responseData，用于存储接口返回数据
      isRequesting: false, // 用于标识是否正在请求接口
      NccStockOptions: [], // 查询NCC仓库信息_1
      materialNameOptions: [], // 查询NCC物料信息_5
      pickerOptions: {
        shortcuts: [
          {
            text: "当天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              // 设置开始时间和结束时间都为当天的零点到当天的23点59分59秒
              start.setHours(0, 0, 0, 0);
              end.setHours(23, 59, 59, 999);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      selectedRows: [], // 用于存储多选的选中行
      confirmLoadingMap: {}, // 每行确认按钮加载状态
    };
  },
  mounted() {
    this.queryOtherOutboundNccList(); // 查询获取其他出库单列表
    this.searchNCCStockList(); // 1、获取NCC仓库信息
  },
  methods: {
    // 根据 fbillflag 返回对应的文字描述
    getBillStatus(flag) {
      const statusMap = {
        1: "作废",
        2: "自由",
        3: "签字",
        4: "审核",
        5: "审核中",
        6: "审核不通过",
        7: "已调差状态",
      };
      return statusMap[flag] || "未知状态";
    },

    // 根据 fbillflag 返回 Element UI 标签的类型
    getTagType(flag) {
      const tagMap = {
        1: "danger", // 默认标签
        2: "", // 默认标签
        3: "success", // 绿色
        4: "info", // 蓝色
        5: "warning", // 黄色
        6: "danger", // 红色
        7: "", // 默认标签
      };
      return tagMap[flag] || ""; // 默认无类型
    },

    // 格式化时间
    formatDate(date) {
      if (!date) return ""; // 如果 `date` 为空或 `null`，返回占位符
      return this.$dayjs(date).isValid()
        ? this.$dayjs(date).format("YYYY-MM-DD")
        : "-";
    },

    // 用于去除指定字段前后的空格
    trimInput(field) {
      this.queryParams[field] = this.queryParams[field].trim();
    },

    // 处理行的展开/收起
    handleExpandChange(row) {
      const index = this.expandKeys.indexOf(row.vbillcode);
      if (index === -1) {
        // 如果当前行未展开，则展开该行，并收起其他行
        this.expandKeys = [row.vbillcode];
      } else {
        // 如果当前行已展开，则收起该行
        this.expandKeys = [];
      }
    },

    // 处理确认按钮点击事件
    handleConfirm(row) {
      // 检查是否正在加载中
      const code = row.vbillcode;
      if (this.confirmLoadingMap[code]) {
        return;
      }
      // 设置加载状态为 true
      this.$set(this.confirmLoadingMap, code, true);

      // 获取当前表头对应的所有表体行
      const detailRows = row.detailData || [];
      console.log("处理确认按钮detailRows=", detailRows);

      // 定义需要拦截的库存状态值（待检和不合格的编码）
      const invalidStatusCodes = [
        "1001A110000000002T08",
        "1001ZZ1000000002XCX4",
      ];

      // 检查是否存在无效库存状态的表体行
      const hasInvalidStatus = detailRows.some((detailRow) =>
        invalidStatusCodes.includes(detailRow.cstateid)
      );
      console.log("处理确认按钮hasInvalidStatus=", hasInvalidStatus);

      const resetLoading = () => {
        this.$set(this.confirmLoadingMap, code, false);
      };

      if (hasInvalidStatus) {
        // 弹出提示框，确认是否继续操作
        this.$confirm(
          "单据中存在待检或不合格的库存状态，确认继续操作吗？",
          "警告",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            this.executeConfirmLogic(row).finally(resetLoading);
          })
          .catch(resetLoading);
      } else {
        this.executeConfirmLogic(row).finally(resetLoading);
      }
    },

    // 封装"处理确认按钮点击事件"的确认逻辑
    executeConfirmLogic(row) {
      // 封装为返回Promise的函数，以便使用finally
      return new Promise((resolve) => {
        const formattedDbilldate = row.dbilldate;
        const vbillcode = row.vbillcode;
        const vbillcodeArray = [vbillcode];
        const initialSignData = {
          dbilldate: formattedDbilldate,
          vbillcode: vbillcodeArray,
          confirmType: "0",
        };
        // console.log("initialSignData=", initialSignData);

        createOtherOutboundConfirm(initialSignData)
          .then((response) => {
            console.log("返回确认response=", response);
            if (response && response.code === 200) {
              this.$message({
                message: response.msg,
                type: "success",
              });

              this.queryOtherOutboundNccList(); // 刷新列表
            } else {
              if (response && response.data.code === 300) {
                const htmlContent = `
                  <div style="
                    max-height: 160px;
                    overflow-y: auto;
                    padding-right: 8px;
                    line-height: 1.6;
                    border: 1px solid #f0f0f0;
                    margin-bottom: 10px;
                  ">
                    ${response.data.msg.replace(/\n/g, "<br/>")}
                  </div>
                  <strong>是否继续确认出库？</strong>
                `;

                this.$confirm(htmlContent, "提示", {
                  confirmButtonText: "继续",
                  cancelButtonText: "取消",
                  dangerouslyUseHTMLString: true,
                  type: "warning",
                })
                  .then(() => {
                    const secondSignData = {
                      ...initialSignData,
                      confirmType: "1",
                    };
                    return createOtherOutboundConfirm(secondSignData);
                  })
                  .then((secondResponse) => {
                    if (secondResponse && secondResponse.code === 200) {
                      this.$message({
                        message: secondResponse.msg,
                        type: "success",
                      });
                      this.queryOtherOutboundNccList();
                    } else {
                      this.$message({
                        message: secondResponse.msg || "二次确认失败",
                        type: "error",
                      });
                    }
                  })
                  .catch((error) => {
                    console.error("二次确认失败", error);
                  });
              } else {
                this.$message({
                  message: response.msg,
                  type: "error",
                });
              }
            }
            resolve(response); // 解析Promise
          })
          // .catch((error) => {
          //   console.error("确认失败", error);
          // });
          .catch((error) => {
            console.error("其他出库单据确认失败", error);
            this.$message({
              message: "操作失败，请稍后重试",
              type: "error",
            });
            resolve(error); // 解析Promise
          });
      });
    },

    // 处理选中变化，更新 selectedRows
    handleSelectionChange(val) {
      this.selectedRows = val;
      console.log("选中的行：", this.selectedRows); // 调试：输出选中的行
    },
    // 处理多选确认按钮点击事件
    handleMultipleConfirm() {
      // console.log("选中的记录：", this.selectedRows);  // 输出选中的行，调试用
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message({
          message: "请至少选择一条记录",
          type: "warning",
        });
        return;
      }

      // 弹出确认框
      this.$confirm("确定要确认这些选中的记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 确认后的逻辑
          const vbillcodes = this.selectedRows.map((row) => row.vbillcode);
          let formattedDbilldate = "";
          if (
            this.queryParams.dbilldate &&
            this.queryParams.dbilldate.length === 2
          ) {
            const [start, end] = this.queryParams.dbilldate;
            formattedDbilldate = `${start}~${end}`;
          }

          const signData = {
            dbilldate: formattedDbilldate,
            vbillcode: vbillcodes,
          };
          console.log("signData=", signData);
          createOtherOutboundConfirm(signData)
            .then((response) => {
              console.log("返回多选确认response=", response);
              if (response && response.code === 200) {
                this.$message({
                  message: response.msg,
                  type: "success",
                });
                // 清空选中行数组，取消勾选
                this.selectedRows = [];
                // 通过ref获取el-table实例并调用clearSelection方法
                this.$refs.tableRef.clearSelection();
                // 查询单据信息列表
                this.queryOtherOutboundNccList();
              } else {
                this.$message({
                  message: response.msg,
                  type: "error",
                });
              }
            })
            .catch((error) => {
              console.log("其他出库单确认失败", error);
            });
        })
        .catch(() => {
          console.log("取消操作");
        });
    },

    // 控制 expandKeys 和 expandedRows 的状态同步更新
    toggleExpand(row) {
      const rowKey = row.vbillcode; // 唯一标识当前行

      // 判断当前行是否已展开
      const isExpanded = this.expandedRows.includes(rowKey);

      // 如果当前行已经展开，点击"收起"，否则点击"查看"
      if (isExpanded) {
        // 当前行已展开：从 expandedRows 和 expandKeys 移除
        this.expandedRows = this.expandedRows.filter((v) => v !== rowKey);
        this.expandKeys = this.expandKeys.filter((v) => v !== rowKey);
      } else {
        // 当前行未展开：清空所有已展开的行，然后将当前行添加到 expandKeys 和 expandedRows
        this.expandKeys = [rowKey];
        this.expandedRows = [rowKey];
      }
    },

    // 页大小变化
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize;
      this.currentPage = 1; // 重置为第一页
      this.queryOtherOutboundNccList(); // 重新查询
    },

    // 当前页变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.queryOtherOutboundNccList(); // 重新查询
    },
    /**
     * 查询获取其他出库单列表
     */
    queryOtherOutboundNccList() {
      this.loading = true; // 设置加载状态为 true

      // 清空旧数据
      this.headerList = []; // +++ 新增清空操作

      let formattedDbilldate = "";
      if (
        this.queryParams.dbilldate &&
        this.queryParams.dbilldate.length === 2
      ) {
        const [start, end] = this.queryParams.dbilldate;
        formattedDbilldate = `${start}~${end}`;
        console.log("成功格式化日期范围:", formattedDbilldate); // 添加这行日志，看是否能正常执行到这一步
      }
      const params = {
        vbillcode: this.queryParams.vbillcode || "", // 单据编号
        dbilldate: formattedDbilldate, // 日期范围
        billStatus: this.queryParams.billStatus || "", // WMS单据状态
        fbillflag: this.queryParams.fbillflag || "", // NCC单据状态
        cwarehouseid: this.queryParams.cwarehouseid || "", // 仓库
        material: this.queryParams.material || "", // 物料

        pageSize: this.pageSize, // 每页条数
        pageNum: this.currentPage, // 当前页数
      };
      console.log("params 数据:", params);

      return getOtherOutboundNccInfo(params)
        .then((response) => {
          this.loading = false; // 请求成功后，设置加载状态为 false
          this.responseData = response.rows;
          // 更新 total
          this.total = response.total;

          // 解析 header 和 details 数据
          if (this.responseData.length > 0) {
            this.headerList = this.responseData.map((item) => {
              const header = item.header;
              header.detailData = item.details; // 存放当前表头对应的明细数据
              return header;
            });
            console.log("headerList 数据:", this.headerList);
            if (response.code === 200) {
              // this.$message({
              //   message: response.msg,
              //   type: 'success'
              // });
              console.log("查询信息=", response.msg);
            } else {
              this.$message({
                message: response.msg,
                type: "error",
              });
            }
          } else {
            this.headerList = []; // 无数据时显示空 +++
            console.log("返回数据为空");
          }
          return this.responseData;
        })
        .catch((error) => {
          this.loading = false;
          console.log("接口请求出错:", error);
          throw error;
        });
    },
    /**
     * 查询操作的回调函数
     */
    handleQuery() {
      console.log("查询参数：", this.queryParams);
      if (this.isRequesting) {
        console.log("当前正在请求中，直接返回，不发起新请求");
        return; // 如果正在请求中，直接返回，不再发起新请求
      }
      this.isRequesting = true; // 设置为正在请求状态

      this.queryOtherOutboundNccList()
        .then(() => {
          this.isRequesting = false; // 请求结束，设置为非请求状态
        })
        .catch((error) => {
          this.isRequesting = false; // 请求出错，同样设置为非请求状态
          console.log("接口请求出错:", error);
        });
    },

    // 1、获取NCC仓库信息
    searchNCCStockList() {
      this.loading = true;
      SearchSelect.searchNCCStockList(this)
        .then(() => {
          // 获取到仓库信息后，更新 NccStockOptions
          this.NccStockOptions = this.NccStockList.map((item) => ({
            label: item.label,
            value: item.value,
          }));
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 5、获取NCC物料信息
    searchSelectNccMaterial(query) {
      SearchSelect.searchSelectNccMaterial(query, this);
    },

    /**
     * 重置表单操作
     */
    resetQuery() {
      this.queryParams = {
        // 单据编号
        vbillcode: "",
        // 单据日期/查询日期范围
        dbilldate: "",
      };
      console.log("已重置查询条件");
    },
  },
};
</script>

<style scoped>
/* 主容器样式：设置内边距，避免紧贴页面边缘 */
.app-container {
  padding: 20px;
}

/* 卡片样式：为每个表单块设置外边距，提升视觉效果 */
.el-card {
  margin-bottom: 20px;
}

.btn el-button {
  margin-bottom: 20px;
}
</style>
